﻿using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Application.Common.Interfaces;
using AutoMapper;
using Common.Attributes;
using Common.Events;
using Domain.Entities.Identity;
using MediatR;

namespace Application.Features.Auth.Commands;

/// <summary>
/// 注册用户
/// </summary>
[Map(typeof(User))]
[Description("注册用户")]
[GroupDescription("授权管理")]
public class RegisterCommand : IRequest<bool>
{
    /// <summary>
    /// 用户名
    /// </summary>
    [Required(ErrorMessage = "用户名是必填的")]
    public string UserName { get; set; }

    /// <summary>
    /// 密码
    /// </summary>
    [Required(ErrorMessage = "密码是必填的")]
    public string Password { get; set; }

    /// <summary>
    /// 确认密码
    /// </summary>
    [Required(ErrorMessage = "确认密码是必填的")]
    public string ConfirmPassword { get; set; }
}
/// <summary>
/// 处理程序
/// </summary>
public class AddUserCommandHandler : IRequestHandler<RegisterCommand, bool>
{
    private readonly IApplicationDbContext _context;
    private readonly IMapper _mapper;

    public AddUserCommandHandler(
        IApplicationDbContext context,
        IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    /// <summary>
    /// 业务逻辑
    /// </summary>
    /// <param name="request">请求参数</param>
    /// <param name="cancellationToken">取消标记</param>
    /// <returns>返回处理结果</returns>
    public async Task<bool> Handle(RegisterCommand request, CancellationToken cancellationToken)
    {
        var registerUser = _mapper.Map<User>(request);
        registerUser.IsActive = true;
        registerUser.PasswordHash = registerUser.CreatePassword(request.Password);
        registerUser.AddDomainEvent(new CreatedEvent<User>(registerUser));
        await _context.Users.AddAsync(registerUser);

        return true;
    }
}